<?php

namespace App\Http\Controllers;

use App\BO\PaymentState\Pay\PayFactory;
use App\BO\PaymentState\PaymentState;
use App\BO\Wechat\WechatFactory;
use App\Entities\PaymentEntity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * 微信通知接口
 * Class WechatNotifyController
 * @package App\Http\Controllers
 */
class WechatNotifyController extends BaseController
{
    /**
     * 微信支付回调接口
     * @param Request $request
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function notify(Request $request)
    {
        $app = WechatFactory::payment();
        $response = $app->handlePaidNotify(function ($message, $fail) {
            Log::info('支付通知信息：', $message);

            $tradeNo = $message['out_trade_no'];
            $payment = PaymentEntity::findByTradeNo($tradeNo);
            if (is_null($payment)) {
                return 'fail';
            }

            $paymentState = new PaymentState($payment);
            if ($paymentState->isPaid()) {
                // 告知微信支付此订单已处理
                return true;
            }

            $payInfo = PayFactory::getPayInfoFromWechatNotify($message['transaction_id']);
            $paymentState->pay($payInfo);

            return true;
        });

        $response->send(); // Laravel 里请使用：return $response;
    }

    /**
     * 微信退款通知接口
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function refundNotify(Request $request)
    {
        $app = WechatFactory::payment();
        $response = $app->handleRefundedNotify(function ($message, $reqInfo, $fail) {
            Log::info('解密后的信息', [$reqInfo]);

            $tradeNo = $reqInfo['out_trade_no'];
            $payment = PaymentEntity::findByTradeNo($tradeNo);
            if (is_null($payment)) {
                Log::warning('订单不存在 out_trade_no = ' . $reqInfo['out_trade_no']);
                return true;
            }

            $paymentState = new PaymentState($payment);
            if (!$paymentState->isRefundWaitingThirdPartNotify()) { // 订单状态不对
                return true;
            }

            // 你的业务逻辑...
            if ($reqInfo['refund_status'] === 'SUCCESS') {
                $paymentState->refundThirdPartConfirmSuccess();
                Log::info('微信退款异步通知' . $payment->getId() . '退成功');
            } else {
                // 退款失败，并将退款状态改成失败
                $paymentState->refundThirdPartConfirmFail();
                Log::info('微信退款异步通知' . $payment->getId() . '退失败');
            }

            return true; // 返回 true 告诉微信“我已处理完成”
        });

        return $response;
    }
}
